package com.edu.controller.address;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.edu.dto.ResultDto;
import com.edu.entity.*;
import com.edu.service.AddressesService;
import com.edu.service.AnnouncementsService;
import com.edu.service.impl.AddressesServiceImpl;
import com.edu.service.impl.AnnouncementsServiceImpl;
import com.edu.utils.JwtUtils;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
 * com.edu.controller.addresses
 * 2024/7/15 8:42
 *
 * @author Fancy
 * @version 1.0
 */
@WebServlet(urlPatterns = {"/addresses/*", "/addresses/user/*"})
public class AddressesController extends HttpServlet{
    AddressesService addressesService = new AddressesServiceImpl();


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        AddressEntity address = ServletHelper.getRequestBodyAsObject(req, AddressEntity.class);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        //从请求头获取token
        String token = req.getHeader("token");
        //返回当前操作用户的基本信息
        Map<String, Object> user = JwtUtils.validateToken(token);

        System.out.println(req.getPathInfo().substring(1));
        int userId = Integer.parseInt(req.getPathInfo().substring(1).split("/")[1]);

        try{
            if(user != null)
            {
                Boolean resultRow = addressesService.addAddress(address, userId);
                if (resultRow) {
                    String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Address information added successfully.");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                } else {
                    String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "添加失败,请检查信息是否正确");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    resp.getWriter().write(rst);
                }
            }
            else
            {
                String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "权限不足");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        }catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        System.out.println(req.getPathInfo().substring(1));
        int userId = Integer.parseInt(req.getPathInfo().substring(1).split("/")[1]);
        List<AddressEntity> addresses = addressesService.getAddressesByUserId(userId);

        try {
            if (addresses == null) {
                String rst = ResultDto.fail(ReturnCode.INTERNAL_SERVER_ERROR.getCode(), "获取所有订单信息失败失败");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.success(addresses);
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        String pathInfo = req.getPathInfo();
        String[] pathParts = pathInfo.split("/");
        int addressId = Integer.parseInt(pathParts[1]);
        int userId = Integer.parseInt(pathParts[3]);

        try {
            int resultRow = addressesService.deleteAddress(addressId, userId);

            if (resultRow >= 1) {
                String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Address information deleted successfully.");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "权限不足");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        AddressEntity address = ServletHelper.getRequestBodyAsObject(req, AddressEntity.class);
        String pathInfo = req.getPathInfo();
        String[] pathParts = pathInfo.split("/");
        int addressId = Integer.parseInt(pathParts[1]);
        int userId = Integer.parseInt(pathParts[3]);


        try {
            int resultRow = addressesService.updAddress(address, addressId, userId);

            if (resultRow >= 1) {
                String rst = ResultDto.fail(ReturnCode.SUCCESS.getCode(), "Address information updated successfully.");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            } else {
                String rst = ResultDto.fail(ReturnCode.NOT_FOUND.getCode(), "更新失败。权限不足。");
                resp.setStatus(HttpServletResponse.SC_OK);
                resp.getWriter().write(rst);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
        }
    }

}
